import { useEffect, useState } from 'react'
import { Form, message, FormInstance } from 'antd'
import { useRecoilValue } from 'recoil'
import { messagePushConfigType, tempalateConfigType, templateTableListDataType } from '../interface/interface'
import {
  messagePushList,
  messageSend,
  recipientThree,
  templateDeleteInterface,
  templateTableList,
  templateAdd,
} from '../service/service'
import { isNullArray, isNullData } from '@/utils'
import { userInfo } from '@/store/userInfo'

// 分页信息
interface pagingType {
  pageSize: number
  pageIndex: number
  totalCount?: number
}
export default () => {
  const user = useRecoilValue(userInfo)

  // 消息推送
  const [form]: [FormInstance] = Form.useForm()
  // 模板管理form
  const [templateForm]: [FormInstance] = Form.useForm()

  // 模板管理的分页
  const [templatePaging, setTemplatePaging] = useState<pagingType>({
    totalCount: 0,
    pageIndex: 1,
    pageSize: 10,
  })

  // 历史推送的分页信息
  const [pageParams, setPageParams] = useState<pagingType>({
    totalCount: 0,
    pageIndex: 1,
    pageSize: 10,
  })

  // 模板管理的表格数据
  const [templateTableListData, setTemplateTableListData] = useState<templateTableListDataType[]>([])
  // 洗一下模板管理的表格数据，把它变成下拉框的格式
  const [templateSelect, setTemplateSelect] = useState([])

  // 控制弹框
  const [templateOpenModal, setTemplateOpenModal] = useState<boolean>(false)
  // 是编辑还是新增？
  const [templateAddAndEdit, setTemplateAddAndEdit] = useState<boolean>(false)

  // 内容
  const [templateContent, setTemplateContent] = useState({
    title: '',
    content: '',
  })
  useEffect(() => {
    console.log('💩💩💩', templateContent)
  }, [templateContent])
  // 点击编辑之后存放的整条数据
  const [templateEditData, setTemplateEditData] = useState<any>({})

  // 获取到的内容存放
  const [contentDatas, setContentDatas] = useState({
    pushMode: [], // 推送方式
    title: '', // 推送标题
    // pushContent: '', // 富文本内容
  })
  const [pushContent, setPushContent] = useState('')
  useEffect(() => {
    console.log('🦢🦢xxxxxxxxxxxxxxxx', contentDatas)
  }, [contentDatas])

  const tabsChangeClick = () => {
    setContentDatas({ ...contentDatas, title: '', pushMode: [] })
    setPushContent('')
    form.resetFields()
  }
  // 存放城市父级id
  const [fatherIds, setFatherIds] = useState<number[]>([])

  // 历史推送模板
  const [historyPushTableData, setHistoryPushTableData] = useState([])

  // 接受人树级结构
  const [three, setThree] = useState([])

  // 接受人数组
  const [valueIds, setValueIds] = useState<number[]>([])
  const getTreeSelect = (value: any) => {
    setValueIds([...value]) // 存放勾选的数据
  }

  // 选择模板，同时回显对应的标题和内容
  const getTemplate = (value: any) => {
    const findTemplateData: any = templateTableListData.find((item: any) => item.id === value)
    console.log('🦢🦢', findTemplateData)
    setContentDatas({ ...contentDatas, title: findTemplateData.title })
    form.setFieldsValue({
      title: findTemplateData.title,
    })
    setPushContent(findTemplateData.content)
  }

  // 获取推送方式
  const getPushMethod = (value: any) => {
    setContentDatas({ ...contentDatas, pushMode: value.join(',') })
  }
  // 获取推送标题
  const getPushTitle = (e: any) => {
    console.log('🦢🦢', e.target.value)
    setContentDatas({ ...contentDatas, title: e.target.value })
  }

  // 历史推送更换页码
  const handleChangePage = async (page: number, pageSize?: number) => {
    await setPageParams((v) => ({
      ...v,
      pageIndex: page,
      pageSize: pageSize || pageParams.pageSize,
    }))
  }

  // 富文本编辑器获取到的内容
  const getEditorValue = (value: any) => {
    console.log('🦢🦢进来了', value)
    setPushContent(value)
    // setContentDatas({ ...contentDatas, pushContent: value })
  }

  // 获取消息推送列表
  const getList = async () => {
    const params = {
      pageSize: pageParams.pageSize,
      pageIndex: pageParams.pageIndex,
      search: {
        type: '',
        title: '',
        content: '',
      },
      searchCount: true,
    }

    const res = await messagePushList(params)
    if (isNullData(res)) {
      setPageParams({ ...pageParams, totalCount: res.data.totalCount })
      setHistoryPushTableData(res.data.items)
    }
  }

  // 确认发送
  const affifmEnter = async () => {
    // 如果接收人不选，就不让进行发送
    if (valueIds.length === 0) {
      message.error('请选择接收人')
      return
    }
    if (pushContent === '') {
      message.error('请输入推送内容')
      return
    }
    if (contentDatas.pushMode.length === 0) {
      message.error('请选择推送方式')
      return
    }
    if (contentDatas.title === '') {
      message.error('请输入推送标题')
      return
    }
    // 查找勾选父级id
    const fathers = valueIds.filter((item) => fatherIds.includes(item))
    // 拿到所有的父级id遍历处理
    const newlist = fathers
      .map((item) => {
        // 遍历的时候去遍历树的原数据   查找元数据中的父级id是否存在于你勾选的父级id中
        const info: any = three.find((val: any) => val.key === item)
        // 如果存在返回当前父级id这条数据的children
        // children中就是当前父级下面的所有医院
        // 返回所有医院的id
        if (info) {
          return info.children.map((ite: any) => ite.value)
        }
      })
      .flat()
    // console.log('fathersfathersfathersfathers🦢🦢', fathers)
    // console.log('我点击了确认发送🦢🦢', newlist)
    // console.log('🦢🦢', newlist.join(','))
    // console.log('🦢🦢', valueIds.filter((item) => item > 10000).join(','))
    const params = {
      type: contentDatas.pushMode || '',
      title: contentDatas.title,
      content: pushContent || '',
      receiveId: newlist.join(',') || valueIds.filter((item) => item > 10000).join(','),
    }
    const res = await messageSend(params)
    console.log('💩💩💩💩💩💩💩💩💩', res)
    if (res.code === 200) {
      message.success('发送成功')
      getList()
      setPushContent('')
      // setContentDatas({ ...contentDatas, pushContent: '' })
      form.resetFields()
    }
    console.log('🦢🦢', res)
  }

  const transformData = (data: any) =>
    // 遍历传递进来的多级数据
    data.map((item: any) => {
      const { id, name, children } = item
      // 重构成新的对象赋值
      const transformedItem = {
        title: name,
        value: id,
        key: id,
        children,
        // checked: false, // 增加全选
      }
      // 如果有多级继续执行
      if (children && children.length > 0) {
        transformedItem.children = children.map((child: any) => ({
          title: child.name,
          value: child.code,
          key: child.code,
        }))
      }
      return transformedItem
    })

  // 获取接受人树形结构
  const recipientThreeData = async () => {
    let ifSignUserLocationId: any = 0
    // console.log('🦢🦢', user.provinceId)
    if (user.accountType === 10) {
      ifSignUserLocationId = user.provinceId
    }
    if (user.accountType === 20) {
      ifSignUserLocationId = user.cityId
    }
    const res = await recipientThree({ signUserLocationId: ifSignUserLocationId })
    // console.log('res🦢🦢', res.data)
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      const newList = res.data.map((item: any) => item.id)
      setFatherIds(newList)
    }
    const threePerson = transformData(res.data)
    setThree(threePerson)
    console.log('🦢🦢threePerson', res.data)
    // console.log('🦢🦢threePerson', res.data)
  }

  // todo 模板管理
  // 获取列表
  const getTemplateTableData = async (pageIndex?: number) => {
    const params = {
      pageIndex: pageIndex || templatePaging.pageIndex,
      searchCount: true,
      pageSize: templatePaging.pageSize,
      search: {},
    }
    const res = await templateTableList(params)
    if (res && res.code === 200) {
      setTemplatePaging({ ...templatePaging, totalCount: res.data.totalCount })
      setTemplateTableListData(res.data.items)

      // if (res.data.items.length === 0) {
      //   setTemplatePaging({ ...templatePaging, pageIndex: 1 })
      // }

      // 洗一下表格过来的数据   用作 消息推送里面的模板选择下拉框
      const template = res.data.items.reduce((acc: any, cur: any) => {
        acc.push({ value: cur.id, label: cur.title })
        return acc
      }, [])
      setTemplateSelect(template)
    }
  }

  // 点击新增打开弹框
  const templateOpenModalClick = () => {
    setTemplateAddAndEdit(false) // false 是在新增
    setTemplateOpenModal(true)
    templateForm.resetFields()
  }

  // 输入框获取内容
  const templateInputValue = (e: any) => {
    setTemplateContent({ ...templateContent, title: e.target.value })
  }

  // 富文本编辑器获取内容
  const auditValue = (value: string) => {
    setTemplateContent({ ...templateContent, content: value })
  }

  // 编辑事件
  const templateEdit = (record: any) => {
    setTemplateContent({ ...templateContent, content: record.content, title: record.title }) // 回显富文本
    templateForm.setFieldsValue({ title: record.title }) // 回显标题
    setTemplateOpenModal(true)
    setTemplateAddAndEdit(true) // ture 是在编辑
    setTemplateEditData(record) // 存以下当前编辑的单行数据
  }

  // 删除事件
  const templateDelete = async (record: any) => {
    const res = await templateDeleteInterface({ id: record.id })
    if (res && res.code === 200) {
      message.success('删除成功')
      if (templateTableListData.length === 1) {
        getTemplateTableData(1)
        setTemplatePaging({ ...templatePaging, pageIndex: 1 })
      }
      getTemplateTableData()
    } else {
      message.error('网络错误')
    }
  }

  // 点击取消关闭弹框
  const templateClearModal = () => {
    setTemplateContent({ ...templateContent, title: '', content: '' })
    setTemplateOpenModal(false) // 关闭弹框
  }

  // 底部按钮保存事件
  const templateSave = async () => {
    // 在新增
    if (!templateAddAndEdit) {
      const params = {
        title: templateContent.title,
        content: templateContent.content,
      }
      const res = await templateAdd(params)
      if (res && res.code === 200 && res.data.status) {
        setTemplateContent({ ...templateContent, content: '' })
        message.success('新增成功')
        setTemplateOpenModal(false)
        getTemplateTableData()
      } else {
        message.info(res.data.msg)
      }
      return
    }

    // 在编辑
    if (templateAddAndEdit) {
      const params = {
        id: templateEditData.id,
        title: templateContent.title,
        content: templateContent.content,
      }
      const res = await templateAdd(params)
      if (res && res.code === 200 && res.data.status) {
        setTemplateContent({ ...templateContent, content: '' })
        message.success('编辑成功')
        setTemplateOpenModal(false)
        getTemplateTableData()
      } else {
        message.info(res.data.msg)
      }
    }
  }

  // 模板管理切换分页
  const templateChangePagingUploadTable = (page: number, pageSizes: number) => {
    setTemplatePaging({
      ...templatePaging,
      pageIndex: page,
      pageSize: pageSizes,
    })
  }

  useEffect(() => {
    console.log('💩💩💩', templatePaging)
  }, [templatePaging])
  useEffect(() => {
    recipientThreeData()
  }, [])

  // 历史推送分页更新表格
  useEffect(() => {
    getList()
  }, [pageParams.pageIndex, pageParams.pageSize])

  // 模板管理分页更新表格
  useEffect(() => {
    getTemplateTableData()
  }, [templatePaging.pageIndex, templatePaging.pageSize])

  // 消息推送,历史推送配置
  const messagePushConfig: messagePushConfigType = {
    form,
    contentDatas,
    getTemplate,
    getPushMethod,
    getPushTitle,
    getTreeSelect,
    getEditorValue,
    affifmEnter,
    historyPushTableData, // 历史推送模板
    three,
    fatherIds,
    handleChangePage,
    pageParams,
    templateSelect,
    pushContent,
    tabsChangeClick,
  }

  // 模板管理配置
  const tempalateConfig: tempalateConfigType = {
    templateInputValue,
    auditValue,
    templateEdit,
    templateDelete,
    templateOpenModalClick,
    templateClearModal,
    templateChangePagingUploadTable,
    templateSave,
    templateOpenModal,
    templateAddAndEdit,
    templateContent,
    templateTableListData,
    templateForm,
    templatePaging,
  }
  return {
    messagePushConfig,
    tempalateConfig,
  }
}
